package com.iot.hmi.controller;

import com.iot.hmi.entity.IotDevice;
import com.iot.hmi.utils.SqliteHelper;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class DeviceInputDialogController {

    @FXML
    private TextField hostTextField;

    @FXML
    private TextField portTextField;

    @FXML
    private ComboBox<String> typeComboBox;

    private IotDevice device;
    private boolean confirmed = false;

    // 添加静态方法来获取当前实例
    private static DeviceInputDialogController instance;

    public static DeviceInputDialogController getInstance() {
        if (instance == null) {
            instance = new DeviceInputDialogController();
        }
        return instance;
    }

    // 保存数据的方法
    public void saveDevice(IotDevice device) {
        this.device = device;
        this.confirmed = true;
        this.hostTextField.setText(device.getProtocolHost());
        this.portTextField.setText(String.valueOf(device.getProtocolPort()));
        this.typeComboBox.setValue(device.getProtocolType());
    }

    // 获取保存的数据
    public IotDevice getDevice() {
        return device;
    }

    // 判断是否确认
    public boolean isConfirmed() {
        return confirmed;
    }

    // 清除数据
    public void clearData() {
        this.device = null;
        this.confirmed = false;
    }
    @FXML
    public void initialize() {
        typeComboBox.getItems().addAll("ModbusTCP", "S7-200", "S7-200SMART", "S7-300", "S7-400", "S7-1200", "S7-1500");
    }

    @FXML
    private void handleConfirmAction() {
        String host = hostTextField.getText();
        String portStr = portTextField.getText();
        String type = typeComboBox.getValue();

        if (host != null && !host.trim().isEmpty() && portStr != null && !portStr.trim().isEmpty() && type != null) {
            try {
                int port = Integer.parseInt(portStr);
                if (port > 0 && port <= 65535) {
                    device = new IotDevice();
                    //生成id
                    device.setId(SqliteHelper.ip2int(host));
                    device.setProtocolHost(host);
                    device.setProtocolPort(port);
                    device.setProtocolType(type);
                    confirmed = true;
                    Stage stage = (Stage) hostTextField.getScene().getWindow();
                    stage.close();
                } else {
                    // 端口范围错误
                    System.out.println("端口范围错误，请输入1到65535之间的数字。");
                }
            } catch (NumberFormatException e) {
                // 端口格式错误
                System.out.println("端口格式错误，请输入有效的数字。");
            }
        } else {
            // 输入字段为空
            System.out.println("请填写所有字段。");
        }
    }

    @FXML
    private void handleCancelAction() {
        confirmed = false;
        Stage stage = (Stage) hostTextField.getScene().getWindow();
        stage.close();
    }

}
